package com.haixiaoke.saas.enterprise.apartment.controller;

import java.math.BigDecimal;
import java.util.List;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.ObjectUtil;
import com.haixiaoke.saas.common.annotation.Log;
import com.haixiaoke.saas.common.annotation.RepeatSubmit;
import com.haixiaoke.saas.common.annotation.TenantScope;
import com.haixiaoke.saas.common.core.domain.AjaxResult;
import com.haixiaoke.saas.common.core.page.TableDataInfo;
import com.haixiaoke.saas.common.enums.BusinessType;
import com.haixiaoke.saas.common.tenant.TenantContext;
import com.haixiaoke.saas.common.utils.poi.ExcelUtil;
import com.haixiaoke.saas.apartment.domain.HousingAllocation;
import com.haixiaoke.saas.apartment.service.IHousingAllocationService;
import com.haixiaoke.saas.house.domain.House;
import com.haixiaoke.saas.system.BaseController;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 房屋配置Controller
 *
 * @author panda
 * @date 2024-03-21
 */
@RestController
@RequestMapping("/enterprise/apartment/allocation")
public class EnterpriseHousingAllocationController extends BaseController {
    @Autowired
    private IHousingAllocationService housingAllocationService;


    /**
     * 查询房屋配置列表
     */
    @PreAuthorize("@ss.hasPermi('enterprise:allocation:list')")
    @GetMapping("/list")
    @TenantScope
    public TableDataInfo list(HousingAllocation housingAllocation) {
        startPage();
        housingAllocation.setTenantId(TenantContext.getTenantId());
        List<HousingAllocation> list = housingAllocationService.selectHousingAllocationList(housingAllocation);
        return getDataTable(list);
    }

    @GetMapping("/listByAllocation")
    @TenantScope
    public TableDataInfo listByAllocation(House house) {
        startPage();
        house.setTenantId(TenantContext.getTenantId());
        List<HousingAllocation> list = housingAllocationService.selectHouseByAllocation(house);
        return getDataTable(list);
    }

    @TenantScope
    @GetMapping("/listByAllocation1")
    public TableDataInfo listByAllocation1(House house) {
        startPage();
        house.setTenantId(TenantContext.getTenantId());
        List<HousingAllocation> list = housingAllocationService.selectHouseByAllocation(house);
        return getDataTable(list);
    }

    /**
     * 统计上下架数量，未配置数量，及全部房屋的数量
     *
     * @return
     */
    @GetMapping("/countByState")
    @TenantScope
    public AjaxResult countByState() {
        return success(housingAllocationService.countByState(TenantContext.getTenantId()));
    }

    /**
     * 导出房屋配置列表
     */
    @PreAuthorize("@ss.hasPermi('enterprise:allocation:export')")
    @Log(title = "房屋配置", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, HousingAllocation housingAllocation) {
        List<HousingAllocation> list = housingAllocationService.selectHousingAllocationList(housingAllocation);
        ExcelUtil<HousingAllocation> util = new ExcelUtil<HousingAllocation>(HousingAllocation.class);
        util.exportExcel(response, list, "房屋配置数据");
    }

    /**
     * 获取房屋配置详细信息
     */
    @PreAuthorize("@ss.hasPermi('enterprise:allocation:query')")
    @GetMapping(value = "/{houseId}")
    public AjaxResult getInfo(@PathVariable("houseId") String houseId) {
        return success(housingAllocationService.selectHousingAllocationByAllocationId(houseId));
    }

    /**
     * 新增房屋配置
     */
    @PreAuthorize("@ss.hasPermi('enterprise:allocation:add')")
    @Log(title = "房屋配置", businessType = BusinessType.INSERT)
    @PostMapping
    @TenantScope
    @RepeatSubmit
    public AjaxResult add(@RequestBody HousingAllocation allocation) {
        if (housingAllocationService.checkAllocationByHouse(allocation.getHouseId())) {
            return AjaxResult.error("该房屋已添加配置信息");
        }
        if (!Pattern.compile("^1[3-9]\\d{9}$").matcher(allocation.getContactPhone()).matches()) {
            return error("手机号格式不正确");
        }
        AjaxResult ajaxResult = checkAllocation(allocation);
        if (ajaxResult != null) {
            return ajaxResult;
        }
        allocation.setCreateBy(getUsername());
        allocation.setTenantId(TenantContext.getTenantId());
        return toAjax(housingAllocationService.insertHousingAllocation(allocation));
    }

    /**
     * 修改房屋配置的上下架状态
     */
    @PreAuthorize("@ss.hasPermi('enterprise:allocation:edit')")
    @Log(title = "房屋配置", businessType = BusinessType.UPDATE)
    @PutMapping("/edit/state")
    @TenantScope
    public AjaxResult editApartmentState(@RequestBody HousingAllocation housingAllocation) {
        if (ObjectUtil.isEmpty(housingAllocation.getAllocationId())) {
            return warn("该房屋未配置，请先配置信息");
        }
        housingAllocation.setUpdateBy(getUsername());
        return toAjax(housingAllocationService.updateHousingAllocationState(housingAllocation));
    }

    public AjaxResult checkAllocation(HousingAllocation housingAllocation) {
        if (!housingAllocation.getApartmentPictureList().isEmpty() && housingAllocation.getApartmentPictureList().size() > 9) {
            return AjaxResult.warn("房屋图片只能上传9张");
        }
        if (housingAllocation.getCheckInTypeList().isEmpty()) {
            return AjaxResult.warn("请选择入住方式");
        }
        int result = housingAllocation.getCashPledge().compareTo(BigDecimal.ZERO);
        if (result <= 0) {
            return AjaxResult.warn("押金只能大于0");
        }
        if (housingAllocation.getCashPledge().scale() > 2) {
            return AjaxResult.warn("押金小数点最多两位小数");
        }
        if (housingAllocation.getHousingPriceList().size() != 7) {
            return AjaxResult.error("房费数据错误");
        }
        boolean housePriceBoolean = housingAllocation.getHousingPriceList().stream()
                .anyMatch(entry -> entry.getHousePrice() == null || entry.getHousePrice().compareTo(BigDecimal.ZERO) <= 0);
        if (housePriceBoolean) {
            return AjaxResult.warn("房费只能大于0");
        }
        boolean priceBoolean = housingAllocation.getHousingPriceList().stream()
                .anyMatch(entry -> entry.getHousePrice().scale() > 2);
        if (priceBoolean) {
            return AjaxResult.warn("房费小数点最多两位小数");
        }
        return null;
    }

    /**
     * 修改房屋配置
     */
    @PreAuthorize("@ss.hasPermi('enterprise:allocation:edit')")
    @Log(title = "房屋配置", businessType = BusinessType.UPDATE)
    @PutMapping
    @TenantScope
    public AjaxResult edit(@RequestBody HousingAllocation housingAllocation) {
        if (!Pattern.compile("^1[3-9]\\d{9}$").matcher(housingAllocation.getContactPhone()).matches()) {
            return error("手机号格式不正确");
        }
        AjaxResult ajaxResult = checkAllocation(housingAllocation);
        if (ajaxResult != null) {
            return ajaxResult;
        }
        housingAllocation.setUpdateBy(getUsername());
        return toAjax(housingAllocationService.updateHousingAllocation(housingAllocation));
    }

    /**
     * 删除房屋配置
     */
    @PreAuthorize("@ss.hasPermi('enterprise:allocation:remove')")
    @Log(title = "房屋配置", businessType = BusinessType.DELETE)
    @DeleteMapping("/{allocationId}")
    public AjaxResult remove(@PathVariable Long allocationId) {
        return toAjax(housingAllocationService.softDeleteHousingAllocationByAllocationId(allocationId));
    }
}
